package com.pur.zsms.weixin.service.impl;

import java.util.List;

import javax.annotation.Resource;

import net.sf.cglib.beans.BeanCopier;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.lianchuang.util.WeixinUtil;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.util.PubFun;
import com.pur.zsms.ordercustommanage.po.OrderDistributorPo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierPo;
import com.pur.zsms.pmsnmanage.role.dao.IRoleDao;
import com.pur.zsms.pmsnmanage.user.dao.IUserDao;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.shopmanage.po.ShopPo;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.supplier.dao.SupplierDao;
import com.pur.zsms.supplier.po.SupplierPo;
import com.pur.zsms.supplier.po.SupplierTypePo;
import com.pur.zsms.supplier.vo.SupplierVo;
import com.pur.zsms.weixin.bean.Data;
import com.pur.zsms.weixin.bean.Data_Day;
import com.pur.zsms.weixin.bean.Data_customerName;
import com.pur.zsms.weixin.bean.Data_customerPhone;
import com.pur.zsms.weixin.bean.Data_first;
import com.pur.zsms.weixin.bean.Data_orderId;
import com.pur.zsms.weixin.bean.Data_orderType;
import com.pur.zsms.weixin.bean.Data_remark;
import com.pur.zsms.weixin.bean.NewOrdersTemplate;
import com.pur.zsms.weixin.bean.Token;
import com.pur.zsms.weixin.service.IWeixinService;
import com.pur.zsms.weixin.utilpay.CommonUtil;
import com.pur.zsms.weixin.web.WeixinControllor;

@Service("weixinService")
public class WeixinServiceImpl implements IWeixinService {
	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(WeixinControllor.class);
	String msg = "";

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Resource(name = "shopService")
	private IShopService shopService;

	@Resource(name = "userDao")
	private IUserDao userDaoImpl;

	@Resource(name = "roleDao")
	private IRoleDao roleDaoImpl;

	@Resource(name = "supplierDao")
	private SupplierDao supplierDao;

	public SupplierDao getSupplierDao() {
		return supplierDao;
	}

	public void setSupplierDao(SupplierDao supplierDao) {
		this.supplierDao = supplierDao;
	}

	public IUserDao getUserDaoImpl() {
		return userDaoImpl;
	}

	public void setUserDaoImpl(IUserDao userDaoImpl) {
		this.userDaoImpl = userDaoImpl;
	}

	public UserPo associationOpenId(UserVo userVo) throws GenericException {
		UserPo userPo = new UserPo();
		List<UserPo> list = userDaoImpl.getUserPoListByUserName(userVo.getUserName());
		if (list != null && list.size() > 0) {
			userPo = list.get(0);
			userPo.setOpenId(userVo.getOpenId().trim());
			userDaoImpl.updateUser(userPo);
		} else {
			msg = "系统没有找到" + userVo.getUserName() + "账号！";
		}

		return userPo;
	}

	// 解除绑定
	public boolean associationOpenIdOut(UserPo userPo) throws GenericException {
		userPo.setOpenId(null);
		userDaoImpl.updateUser(userPo);

		return true;
	}

	/**
	 * 发送模板消息 appId 公众账号的唯一标识 appSecret 公众账号的密钥 openId 用户标识
	 */
	public void send_template_message(String appId, String appSecret, String openId) throws GenericException {

		Token token = CommonUtil.getToken(appId, appSecret);
		String access_token = token.getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

		NewOrdersTemplate temp = new NewOrdersTemplate();
		Data data = new Data();
		Data_first first = new Data_first();
		Data_Day Day = new Data_Day();
		Data_orderId orderId = new Data_orderId();
		Data_orderType orderType = new Data_orderType();
		Data_customerName customerName = new Data_customerName();
		Data_customerPhone customerPhone = new Data_customerPhone();
		Data_remark remark = new Data_remark();

		first.setValue("收到一个新的订单");
		first.setColor("#173177");
		Day.setValue("14时56分");
		Day.setColor("#173177");
		orderId.setValue("1002");
		orderId.setColor("#173177");
		orderType.setValue("客户订单");
		orderType.setColor("#173177");
		customerName.setValue("测试人员");
		customerName.setColor("#173177");
		customerPhone.setValue("13222222222");
		customerPhone.setColor("#173177");
		remark.setValue("请及时处理您的订单");
		remark.setColor("#173177");

		data.setFirst(first);
		data.setDay(Day);
		data.setOrderId(orderId);
		data.setOrderType(orderType);
		data.setCustomerName(customerName);
		data.setCustomerPhone(customerPhone);
		data.setRemark(remark);
		temp.setTouser(openId);
		// temp.setTemplate_id("YtO2XATY0VtRbgE4jWWNl-Zdc992FDdguhMUbomNkA0");
		temp.setTemplate_id("8Pl45OsAOMjwWk7iz0MUrBoMmncwPeJBPNmYaYdlni8");

		temp.setUrl("http://weixin.qq.com/download");
		temp.setTopcolor("#173177");
		temp.setData(data);

		String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
		JSONObject jsonObject = WeixinUtil.httpRequestToJsonObject(url, "POST", jsonString);
		System.out.println(jsonObject);
		int result = 0;
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		log.info("模板消息发送结果：" + result);
	}

	/**
	 * 发送模板消息 appId 公众账号的唯一标识 appSecret 公众账号的密钥 openId 用户标识
	 */
	public void send_template_message_for_commitMaterOrderList(String appId, String appSecret, String openId, OrderSupplierPo orderSupplierPo)
			throws GenericException {
		ShopPo shopPo = shopService.getShopPo(orderSupplierPo.getOrdCustId());
		// 查询经理电话
		List<UserPo> userPoList = userDaoImpl.getUserForShopByShopIdAndLevel(orderSupplierPo.getOrdCustId(), 4);
		UserPo userPo = null;
		if (userPoList != null && userPoList.size() > 0) {
			userPo = userPoList.get(0);
		}
		Token token = CommonUtil.getToken(appId, appSecret);
		String access_token = token.getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

		NewOrdersTemplate temp = new NewOrdersTemplate();
		Data data = new Data();
		Data_first first = new Data_first();
		Data_Day Day = new Data_Day();
		Data_orderId orderId = new Data_orderId();
		Data_orderType orderType = new Data_orderType();
		Data_customerName customerName = new Data_customerName();
		Data_customerPhone customerPhone = new Data_customerPhone();
		Data_remark remark = new Data_remark();

		first.setValue("收到一个新的订单");
		first.setColor("#173177");
		Day.setValue(orderSupplierPo.getOrdDate());
		Day.setColor("#173177");
		orderId.setValue(String.valueOf(orderSupplierPo.getOrdId()));
		orderId.setColor("#173177");
		orderType.setValue("客户订单");
		orderType.setColor("#173177");
		customerName.setValue(shopPo.getShopName());
		customerName.setColor("#173177");
		if (userPo != null) {
			customerPhone.setValue(String.valueOf(userPo.getUserPhone()));
		} else {
			customerPhone.setValue("");
		}
		customerPhone.setColor("#173177");
		remark.setValue("请及时处理您的订单");
		remark.setColor("#173177");

		data.setFirst(first);
		data.setDay(Day);
		data.setOrderId(orderId);
		data.setOrderType(orderType);
		data.setCustomerName(customerName);
		data.setCustomerPhone(customerPhone);
		data.setRemark(remark);
		temp.setTouser(openId);
		// temp.setTemplate_id("YtO2XATY0VtRbgE4jWWNl-Zdc992FDdguhMUbomNkA0");
		temp.setTemplate_id("8Pl45OsAOMjwWk7iz0MUrBoMmncwPeJBPNmYaYdlni8");

		temp.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx64bdfb1d6682c965&redirect_uri=http%3A%2F%2Fwww.dailycooks.cn%2Fweixintest%2FweixinOrderForSupToCust.do&response_type=code&scope=snsapi_userinfo&state="
				+ orderSupplierPo.getOrdId() + "#wechat_redirect");
		temp.setTopcolor("#173177");
		temp.setData(data);

		String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
		JSONObject jsonObject = WeixinUtil.httpRequestToJsonObject(url, "POST", jsonString);
		System.out.println(jsonObject);
		int result = 0;
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		log.info("模板消息发送结果：" + result);
	}

	/**
	 * 发送模板消息 appId 公众账号的唯一标识 appSecret 公众账号的密钥 openId 用户标识
	 */
	public void send_template_message_for_commitMaterOrderForUpdate(String appId, String appSecret, String openId, OrderSupplierPo orderSupplierPo)
			throws GenericException {
		ShopPo shopPo = shopService.getShopPo(orderSupplierPo.getOrdCustId());
		// 查询经理电话
		List<UserPo> userPoList = userDaoImpl.getUserForShopByShopIdAndLevel(orderSupplierPo.getOrdCustId(), 4);
		UserPo userPo = null;
		if (userPoList != null && userPoList.size() > 0) {
			userPo = userPoList.get(0);
		}
		Token token = CommonUtil.getToken(appId, appSecret);
		String access_token = token.getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

		NewOrdersTemplate temp = new NewOrdersTemplate();
		Data data = new Data();
		Data_first first = new Data_first();
		Data_Day Day = new Data_Day();
		Data_orderId orderId = new Data_orderId();
		Data_orderType orderType = new Data_orderType();
		Data_customerName customerName = new Data_customerName();
		Data_customerPhone customerPhone = new Data_customerPhone();
		Data_remark remark = new Data_remark();

		first.setValue("订单已被修改请确认！");
		first.setColor("#173177");
		Day.setValue(orderSupplierPo.getOrdDate());
		Day.setColor("#173177");
		orderId.setValue(String.valueOf(orderSupplierPo.getOrdId()));
		orderId.setColor("#173177");
		orderType.setValue("客户订单");
		orderType.setColor("#173177");
		customerName.setValue(shopPo.getShopName());
		customerName.setColor("#173177");
		if (userPo != null) {
			customerPhone.setValue(String.valueOf(userPo.getUserPhone()));
		} else {
			customerPhone.setValue("");
		}
		customerPhone.setColor("#173177");
		remark.setValue("请及时处理您的订单");
		remark.setColor("#173177");

		data.setFirst(first);
		data.setDay(Day);
		data.setOrderId(orderId);
		data.setOrderType(orderType);
		data.setCustomerName(customerName);
		data.setCustomerPhone(customerPhone);
		data.setRemark(remark);
		temp.setTouser(openId);
		// temp.setTemplate_id("YtO2XATY0VtRbgE4jWWNl-Zdc992FDdguhMUbomNkA0");
		temp.setTemplate_id("8Pl45OsAOMjwWk7iz0MUrBoMmncwPeJBPNmYaYdlni8");
		temp.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx64bdfb1d6682c965&redirect_uri=http%3A%2F%2Fwww.dailycooks.cn%2Fweixintest%2FweixinOrderForSupToCust.do&response_type=code&scope=snsapi_userinfo&state="
				+ orderSupplierPo.getOrdId() + "#wechat_redirect");
		temp.setTopcolor("#173177");
		temp.setData(data);

		String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
		JSONObject jsonObject = WeixinUtil.httpRequestToJsonObject(url, "POST", jsonString);
		System.out.println(jsonObject);
		int result = 0;
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		log.info("模板消息发送结果：" + result);
	}

	public void send_template_message_for_commitMaterOrderForDistributor(String appId, String appSecret, String openId,
			OrderDistributorPo orderDistributorPo) throws GenericException {
		SupplierPo supplierPo = supplierDao.getSupPoBySupId(String.valueOf(orderDistributorPo.getOrdDistributorId()));

		Token token = CommonUtil.getToken(appId, appSecret);
		String access_token = token.getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

		NewOrdersTemplate temp = new NewOrdersTemplate();
		Data data = new Data();
		Data_first first = new Data_first();
		Data_Day Day = new Data_Day();
		Data_orderId orderId = new Data_orderId();
		Data_orderType orderType = new Data_orderType();
		Data_customerName customerName = new Data_customerName();
		Data_customerPhone customerPhone = new Data_customerPhone();
		Data_remark remark = new Data_remark();

		first.setValue("收到一个新的分货商订单");
		first.setColor("#173177");
		Day.setValue(orderDistributorPo.getOrdDate());
		Day.setColor("#173177");
		orderId.setValue(String.valueOf(orderDistributorPo.getOrdId()));
		orderId.setColor("#173177");
		orderType.setValue("分货商订单");
		orderType.setColor("#173177");
		customerName.setValue(supplierPo.getCompanyName());
		customerName.setColor("#173177");
		customerPhone.setValue(supplierPo.getMobile());
		customerPhone.setColor("#173177");
		remark.setValue("请及时处理您的订单");
		remark.setColor("#173177");

		data.setFirst(first);
		data.setDay(Day);
		data.setOrderId(orderId);
		data.setOrderType(orderType);
		data.setCustomerName(customerName);
		data.setCustomerPhone(customerPhone);
		data.setRemark(remark);
		temp.setTouser(openId);
		// temp.setTemplate_id("YtO2XATY0VtRbgE4jWWNl-Zdc992FDdguhMUbomNkA0");
		temp.setTemplate_id("8Pl45OsAOMjwWk7iz0MUrBoMmncwPeJBPNmYaYdlni8");

		temp.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx64bdfb1d6682c965&redirect_uri=http%3A%2F%2Fwww.dailycooks.cn%2Fweixintest%2FweixinOrder.do&response_type=code&scope=snsapi_userinfo&state="
				+ orderDistributorPo.getOrdId() + "#wechat_redirect");
		temp.setTopcolor("#173177");
		temp.setData(data);

		String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
		JSONObject jsonObject = WeixinUtil.httpRequestToJsonObject(url, "POST", jsonString);
		System.out.println(jsonObject);
		int result = 0;
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		log.info("模板消息发送结果：" + result);
	}
}
